<?php
namespace app\know\controller;

use app\know\controller\AdminKnowBaseController;
use app\know\validate\GrammarValidate;
use app\know\validate\GrammarExampleValidate;
use app\know\validate\GrammarQuestionValidate;
use app\know\model\GrammarModel;
use app\know\model\MaterialModel;
use app\know\model\GrammarExampleModel;
use app\know\model\GrammarQuestionModel;
use app\know\model\SysConfigModel;
use think\facade\Db;
use think\facade\Log;

/**
 * Class AdminNewWordController 语法管理控制器
 * @package app\know\controller
 */
class AdminGrammarController extends AdminKnowBaseController
{
    /**
     * 生词管理
     * @adminMenu(
     *     'name'   => '语法管理',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 36000,
     *     'icon'   => '',
     *     'remark' => '语法管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_grammar_index_view');

        if (!empty($content)) 
		{
            return $content;
        }

        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $nav = $this->request->param('nav', 'list');

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();
        $w = [
            ['is_delete', '=', 0],
            ['type', 'in', ['GRAMMAR']]
        ];
        $rows = SysConfigModel::where($w)->order('order_number', 'desc')->select();
        $grammars = [];
        
        foreach($rows as $k => $v) 
        {
            if ($v['type'] == 'GRAMMAR') 
            {
                array_push($grammars, $v);
            }
        }
        
        $this->assign('grammars', $grammars);
		$this->assign('materials', $materials);
        $this->assign('material_uuid', $material_uuid);
        $this->assign('chapter_uuid', $chapter_uuid);
        $this->assign('nav', $nav);
        
        return $this->fetch();
    }

    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.is_delete' => 0 ];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }
        if ($material_uuid)
        {
            $where['a.material_uuid'] = $material_uuid;
        }
        $model = new GrammarModel();

        $count = $model->where($where)->alias('a')->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_material c', 'a.material_uuid = c.uuid')
                    ->leftJoin('cmf_know_chapter d', 'a.chapter_uuid = d.uuid and a.material_uuid = d.relate_uuid')
                    ->page($pageNumber, $pageSize)
                    ->field('a.*, c.name as teaching_name, d.name as chapter_name')
                    ->select();
        
        foreach ($rows as $v)
        {
            $v['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($v['analysis']));  
        }
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];
        
        try 
		{
			$model = new GrammarModel();
			$param['uuid'] = $model->getUUID();
            $this->validateFailError($param, 'Grammar.add');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        Db::startTrans();
        try 
        {
            $row = GrammarModel::create($param);
            if (empty($row)) 
            {
                throw new Exception('语法添加失败');
            }
            // 词汇示例
            $model = new GrammarExampleModel();
            $example = $param['example'];
            foreach(json_decode(htmlspecialchars_decode($example), true) as $exp)
            {
                $exp['create_user'] = $user['user_login'];
                $exp['uuid'] = $model->getUUID();
                $exp['grammar_uuid'] = $param['uuid'];
                $this->validateFailError($exp, 'GrammarExample.add');
                $row = GrammarExampleModel::create($exp);
                if (empty($row)) 
                {
                    throw new Exception('示例添加失败');
                }
            }

            // 试题
            $question = $param['question'];
            foreach(json_decode(htmlspecialchars_decode($question), true) as $qus)
            {
                $qus['create_user'] = $user['user_login'];
                $qus['grammar_uuid'] = $param['uuid'];
                $this->validateFailError($qus, 'GrammarQuestion.add');
                $row = GrammarQuestionModel::create($qus);
                if (empty($row)) 
                {
                    throw new Exception('关联试题添加失败');
                }
            }
            Db::commit();
        } 
        catch (\Exception $e) 
        {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->opLog([
            'table_name' => $model->getTableName(),
            'sql' => GrammarModel::getLastSql(),
            'create_user' => $user['user_login'],
        ]);
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'NewWord.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
		{
            NewWordModel::where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => (new NewWordModel())->getTableName(),
                'sql' => NewWordModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'Grammar.edit');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        Db::startTrans();
        try 
		{
            $example = $param['example'];
            $question = $param['question'];

            $d = GrammarModel::find($id);
            $aF = ['chapter_uuid', 'material_uuid', 'content', 'analysis', 'grammar_code', 'order_number', 'is_delete',
            'is_enable', 'create_user', 'create_datetime', 'modify_user', 'modify_datetime'];
            GrammarModel::update($param, ['id' => $id], $aF);
            Log::debug(__CLASS__ . __FUNCTION__ . '001');
            // 示例
            $nweModel = new GrammarExampleModel();
            foreach(json_decode(htmlspecialchars_decode($example), true) as $exp)
            {
                Log::debug(__CLASS__ . __FUNCTION__ . '003');
                if ($exp['id'])
                {
                    $exp['modify_user'] = $user['user_login'];
                    $exp['modify_datetime'] = date("Y-m-d H:i:s");
                    $this->validateFailError($exp, 'GrammarExample.edit');

                    $aF = ['origin', 'content', 'translate', 'order_number', 'is_delete',
                    'is_enable', 'create_user', 'create_datetime', 'modify_user', 'modify_datetime'];
                    GrammarExampleModel::update($exp, ['id' => $exp['id']], $afExample);
                }
                else
                {
                    $exp['create_user'] = $user['user_login'];
                    $exp['uuid'] = $nweModel->getUUID();
                    $exp['grammar_uuid'] = $d['uuid'];
                    $this->validateFailError($exp, 'GrammarExample.add');
                    $row = GrammarExampleModel::create($exp);
                    if (empty($row)) 
                    {
                        throw new Exception('词汇示例编辑失败');
                    }
                }
                Log::debug(__CLASS__ . __FUNCTION__ . '004');
            }
            Log::debug(__CLASS__ . __FUNCTION__ . '005');
            
			// 试题
            $nwepModel = new GrammarQuestionModel();
            foreach(json_decode(htmlspecialchars_decode($question), true) as $exp_q)
            {
				if (empty($exp_q['grammar_uuid']) == false)
                {
					continue;
				}
                $exp_q['create_user'] = $user['user_login'];
                $exp_q['grammar_uuid'] = $d['uuid'];
                $this->validateFailError($exp_q, 'GrammarQuestion.add');
                $row = GrammarQuestionModel::create($exp_q);
                if (empty($row)) 
                {
                    throw new Exception('试题添加失败');
                }
            }
            Log::debug(__CLASS__ . __FUNCTION__ . '006');
            $this->opLog([
                'table_name' => (new GrammarModel())->getTableName(),
                'sql' => GrammarModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
            Db::commit();
        } 
		catch (\Throwable $th) 
		{
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('修改成功');
    }

    public function maxOrder()
    {
        $order = GrammarModel::max('order_number');
        $this->success('', '', $order);
    }

    public function search()
    {
        $txt = $this->request->param('txt', '');

        $model = new GrammarModel();
        $rows = $model->where('a.content','like', $txt . '%')
                    ->alias('a')
                    ->page(1, 10)
                    ->select();
                
        $this->success('', null, $rows);
    }

    public function getItem()
    {
        $id = $this->request->param('id', '');

        $where = ['a.is_delete' => 0, 'a.id' => $id];
        $model = new GrammarModel();
        $row = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_material c', 'a.material_uuid = c.uuid')
                    ->leftJoin('cmf_know_chapter d', 'a.chapter_uuid = d.uuid and a.material_uuid = d.relate_uuid')
                    ->field('a.*, c.name as teaching_name, d.name as chapter_name')
                    ->find();
        $row['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($row['analysis']));

        $row['example'] = GrammarExampleModel::where(['is_delete' => 0, 'grammar_uuid' => $row['uuid']])->select();
        
        $qmodel = new GrammarQuestionModel();
        $row['question'] = $qmodel->where(['grammar_uuid' => $row['uuid']])
                                ->alias('a')
                                ->leftJoin('cmf_know_question b', 'a.question_uuid = b.uuid')
                                ->leftJoin('cmf_know_question_content c', 'b.uuid = c.question_uuid')
                                ->field('a.*, b.type_alias, c.content, c.answer')
                                ->select();
        foreach($row['question'] as $ques)
        {
            $ques['content'] = htmlspecialchars_decode(htmlspecialchars_decode($ques['content']));
        }

        $this->success('', null, $row);
    }

}
